package javabasic.singleton.lanhanshi;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * synchronize  线程安全的懒汉式单例模式
 */
public class Singleton05 {
    private static Singleton05 INSTANCE;
    private Singleton05(){
        System.out.println("创建对象");
    }
    public static synchronized Singleton05 getInstance(){
        if (INSTANCE==null){
            INSTANCE=new Singleton05();
        }
        return INSTANCE;
    }

    public static void main(String[] args) throws Exception{
        Callable<Singleton05> singleton05Callable = new Callable<Singleton05>() {
            @Override
            public Singleton05 call() throws Exception {
                return Singleton05.getInstance();
            }
        };
        ExecutorService threadPool = Executors.newFixedThreadPool(2);
        Future<Singleton05> future = threadPool.submit(singleton05Callable);
        Future<Singleton05> future1 = threadPool.submit(singleton05Callable);
        Singleton05 instance = future.get();
        Singleton05 instance1 = future1.get();
        System.out.println(instance==instance1);
        threadPool.shutdown();
    }
}
